#ifndef ABSTRACTUPLOADER_H
#define ABSTRACTUPLOADER_H

/*
 */


#include <QObject>
#include "PluginsInterface.h"
#include <QSettings>
#include <QListIterator>
#include <QtDebug>
#include <QtNetwork>
class QIODevice;
#include <QHttpRequestHeader>
#include <QNetworkAccessManager>
#include "UploadWorker.h"
struct HostingParams;

class AbstractUploader : public QObject, public uploadPluginClass
{
	Q_OBJECT
public:
	AbstractUploader();
	~AbstractUploader();
public slots:
	// This function called from main app. It starts process.
	void startUpload(QList<ImageToUpload> images, QObject *mainApp);
protected:
	// Some holders
	HostingParams Hosting; // Hosting parameters
	QObject *mainApp; // Signal stratum from-to main application
	bool requestAborted; // Indicator
	int maxParallelThreads; // Preset. Parallel upload limiter. Sublacc will set it.
	int imagesAtOnce; // Preset. Images per POST query limiter. Sublass will set it.
	QList<UploadWorker*> uploadWorkersRunning; // Pointers to running and finished workers
	QList<UploadWorker*> uploadWorkersFinished;
	QList<ImageToUpload> allImages;
	inline QNetworkAccessManager* getNetManager() { return netManager; } // Getter for subclasses
	// Subclass should reimplement this:
	// Sessions support
	virtual void authorizeAndUpload() { emit authorized(); } // Default will not try anything
	// Parallel upload support. Just call new WorkerClass()
	virtual UploadWorker* newUploadWorker() = 0; // Subclass should create worker's subclasses

private:
	// This is a flow-control
	void upload(); // Runs worker
	void checkAllDone(); // Called on every workker finished to guess where all uploaded
	void finished(); // Called when all uploaded
	bool limitAllow(); // Check whether number of running workers in not very big
	// some holders
	QNetworkAccessManager *netManager;
	// images for uploading
	QListIterator<ImageToUpload> *imageIterator;
	void checkLinksCount(QList<UploadResult> &res);
	QList<UploadResult> cancelLastImages();

private slots:
	void cancelClicked(); // Main app requests cancel
	void uploadNextFile(); // called to start next worker
	void workerFinished(); // called when worker finished
	// Subclass may reimplement it if need
	// Sessions support
	virtual void authReqFinished() {  } // Slot for 'finshed' SIGNAL from auth req
signals:
	// Signal to main app
	void totalError(QString); // can't upload files at all.
	void uploadCompleted(QList<UploadResult> result); // all uploaded
	void startNextFile(int); // main app whants to know about progress of every file
	// Sessions support
	void authorized(); // SESSION STARTED, BEGIN UPLOAD
	void authError(QString errorString); // ERROR HAPPENED, WILL NOT UPLOAD
};


#endif // ABSTRACTUPLOADER_H
